﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Needle.Framework;
using System.ComponentModel.Design;
using Needle.Utils.Extensions;
using System.ComponentModel;
using Needle.DevToolkit.Services.UI;
using Needle.Utils;

namespace Needle.DevToolkit.Services
{
    public class ComponentLoader : ServiceBase, IComponentLoader
    {

        public ComponentLoader(IServiceProvider serviceProvider)
            : base(serviceProvider)
        {
            if (!Services.ContainsService<IContainer>())
                throw new ArgumentException("serviceProvider does not provide a container");
        }

        public object LoadComponent(Type type)
        {
            object plugin = Activator.CreateInstance(type);

            if (plugin is IComponent)
            {
                var container = Services.GetService<IContainer>();
                var component = (IComponent)plugin;
                var commandService = Services.GetService<ICommandService>();
                try
                {
                    if (container != null)
                        container.Add(component);
                    commandService.AddVerbs(component);
                }
                catch
                {
                    if (container != null)
                        container.Remove(component);
                    
                    commandService.RemoveVerbs(component);

                    throw;
                }
            }
            if (plugin is IInitializable)
                ((IInitializable)plugin).Initialize();

            return plugin;
        }

        public TComponent LoadComponent<TComponent>()
        {
            return (TComponent)LoadComponent(typeof(TComponent));
        }

        protected override Type[] ExposedServices
        {
            get { return new Type[] { typeof(IComponentLoader) }; }
        }
    }
}